// pages/schools/schools.js
import {
  apiGetBizSchoolsInfoPublic,
  mentorMessage,
  apiSelectCommentsBySchoolId,
  deleteComment,
  likeComment,
  addUserStars,
  apiGetDepartmentBySchoolId
} from '../../utils/http/api'
const dictionary = wx.getStorageSync('dictionary')
import ActionSheet, {
  ActionSheetTheme
} from 'tdesign-miniprogram/action-sheet/index';
import evn from "../../utils/http/evn"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    dictionary,
    // 状态栏高度，用于自定义导航栏
    statusBarHeight: 44,
    // 导航栏高度
    navBarHeight: 44,
    // 状态栏内边距
    statusbarpadding: 0,
    userInfo: {},
    picUrl: evn.dev.baseUrl + '/',
    url: evn.dev.baseUrl,
    aboardList: [],
    current: 0,
    autoplay: true,
    duration: 500,
    interval: 5000,
    loadingFlag: true,
    isExpanded: false, // 控制展开状态
    swiperList: [],
    swiperList2: [],
    url: evn.dev.baseUrl,
    imgBaseUrl: evn.dev.imgUrl,
    schoolId: 0,
    allLanguageList: [],


    currentIndex: 0, // 当前选中的索引
    languageValue: '',
    showLength: 5, // 展示的几条
    isBtnFlag: false,
    teachLanguage: 1,
    languageList: [],
    degreeList: [],
    videoList: [],
    isShare: false,

    //新属性
    schoolInfo: {},
    commentsList: [],
    departmentList: [],
    schoolName: '',
    bannerPics: [],
    swiperImages: [],
    mentorList: [],
    mentorAvatars: [
      "/img/Avatar01.png",
      "/img/Avatar02.png",
      "/img/Avatar03.png",
      "/img/Avatar04.png",
      "/img/Avatar05.png",
    ],
    langIcons: [
      "/img/lang1.png",
      "/img/lang2.png",
      "/img/lang3.png",
      "/img/lang4.png",
      "/img/lang5.png",
    ],
    openDateCss: [
      "red",
      "blue",
    ],
    languageText: '',
    openDateText: '',
    languageValue: [],
    openDateValue: [],
    languageTitle: '',
    openDateTitle: '',
    languages: [{
        label: '中文',
        value: '1'
      },
      {
        label: '日语',
        value: '2'
      },
      {
        label: '韩语',
        value: '3'
      },
      {
        label: '英文',
        value: '4'
      }
    ],
    openDates: [{
        label: '春季',
        value: '1'
      },
      {
        label: '秋季',
        value: '2'
      }
    ],
    openDatesCheckedList: [],
    apiOpeningDateId: "", //被选中的开学时间
    languageLable: "授课语言",
    openDateLable: "开学时间",
    schooltags: [],
    degreeTypeLabel: '',
    eduPlanName: '',
    placeName: '',
    swiperLogo: [
      "/hanguo2.png",
      "/xibanya2.png",
      "/xinjiapo2.png",
      "/zhongguo2.png",
      "/gangao2.png",
    ],
    showSticky: false,
    stickyVisible: false,
    feeType: '', //学费类型

    // 图片预览状态
    viewerVisible: false,
    viewerImages: [],
    viewerIndex: 0,
  },

  // 轮播切换事件
  onSwiperChange(e) {
    this.setData({
      currentIndex: e.detail.current
    });
  },

  // 点击缩略图切换
  onThumbnailTap(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      currentIndex: index
    });
  },

  toggleExpand() {
    this.setData({
      isExpanded: !this.data.isExpanded
    });
  },

  handleClick(e) {
    //判断是否登录
    let userId = wx.getStorageSync('userInfo') == null || wx.getStorageSync('userInfo') == "" ? 0 : this.data.userInfo.id;
    if (userId == 0) {
      wx.navigateTo({
        url: '/pages/index/login',
      })
    }
    wx.navigateTo({
      url: '/pages/schools/comments/comment?schoolId=' + this.data.schoolId + '&schoolName=' + this.data.schoolInfo.name + '&eduPlanName=' + this.data.eduPlanName,
    })
  },

  goComments(e) {
    let id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '/pages/schools/comments/info?id=' + id + '&schoolName=' + this.data.schoolInfo.name + '&schoolId=' + this.data.schoolInfo.id + '&eduPlanName=' + this.data.eduPlanName,
    })
  },
  goProfession(e) {
    let id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '/pages/schools/profession?id=' + id + '&schoolId=' + this.data.schoolInfo.id
    })
  },


  goBack() {
    const pages = getCurrentPages();
    if (pages && pages.length > 1) {
      wx.navigateBack()
    } else {
      wx.navigateTo({
        url: '/pages/area/china/china',
      });
    }
  },


  // 加载更多
  clickMorn() {
    if (this.data.departmentList.length > this.data.showLength) {
      this.setData({
        showLength: this.data.departmentList.length
      })
    } else {
      this.setData({
        showLength: 5
      })
    }
  },





  // 点赞
  addLike(e) {
    let commentId = e.currentTarget.dataset.id
    let type = e.currentTarget.dataset.type
    let params = {
      commentId, // 讨论Id
      wechatUserId: this.data.userInfo.id, //点赞人id
      type //1是点赞，0是取消点赞
    }
    likeComment(params).then((res) => {
      let list = this.data.commentsList
      let indexs = ''
      list.forEach((item, index) => {
        if (item.id === commentId) {
          indexs = index
        }
      })
      list[indexs].isLike = type
      if (list[indexs].isLike === 1) {
        ++list[indexs].likeCount
      } else {
        --list[indexs].likeCount
      }
      this.setData({
        commentsList: list
      })

    })
  },

  // 打开图片预览
  openImageViewer(e) {
    const {
      urls,
      index
    } = e.currentTarget.dataset;
    const images = Array.isArray(urls) ? urls : [];
    this.setData({
      viewerImages: images,
      viewerIndex: Number(index) || 0,
      viewerVisible: true,
    });
  },

  // 关闭图片预览
  closeImageViewer() {
    this.setData({
      viewerVisible: false
    })
  },

  // 受控属性回调：关闭图片预览
  onViewerVisibleChange(e) {
    const {
      visible
    } = e.detail || {};
    this.setData({
      viewerVisible: !!visible
    });
  },

  // 点击关闭按钮的事件（兼容组件的 close 事件）
  onViewerClose() {
    this.setData({
      viewerVisible: false
    });
  },

  // 时间处理
  getTimeDescription(datetime) {
    const currentTime = new Date();
    const targetTime = new Date(datetime);
    const timeDiff = currentTime.getTime() - targetTime.getTime();
    const minutes = Math.floor(timeDiff / (1000 * 60));
    const hours = Math.floor(minutes / 60);
    const days = Math.floor(hours / 24);

    if (minutes < 5) {
      return '刚刚';
    } else if (minutes < 60) {
      return `${minutes}分钟前`;
    } else if (hours < 24) {
      return `${hours}小时前`;
    } else if (days < 10) {
      return `${days}天前`;
    } else {
      const month = targetTime.getMonth() + 1;
      const day = targetTime.getDate();
      return `${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}`;
    }
  },

  // 时间处理
  getTimeDate(datetime) {
    const currentTime = new Date();
    const targetTime = new Date(datetime);
    const timeDiff = currentTime.getTime() - targetTime.getTime();
    const minutes = Math.floor(timeDiff / (1000 * 60));
    const hours = Math.floor(minutes / 60);
    const month = targetTime.getMonth() + 1;
    const year = targetTime.getFullYear();
    const day = targetTime.getDate();
    return `${year}` + '年' + `${month < 10 ? '0' + month : month}月${day < 10 ? '0' + day : day}日`;
  },

  // 查询讨论列表
  getCommentInfoList() {
    let userId = wx.getStorageSync('userInfo') == null || wx.getStorageSync('userInfo') == "" ? 0 : this.data.userInfo.id;
    this.setData({
      loadingFlag: true
    })
    let params = {
      pageNum: 1,
      pageSize: 20,
      schoolId: this.data.schoolId,
      wechatUserId: userId
    }
    apiSelectCommentsBySchoolId(params).then((res) => {
      if (res.data && res.data.length) {
        res.data = res.data.map((item) => {
          item.createdAt = this.getTimeDescription(item.createdAt),
            item.nickName = item.nickName == null || item.nickName == '' ? '匿名用户' : item.nickName
          return item
        })
        this.setData({
          commentsList: res.data
        })
      } else {
        this.setData({
          commentsList: []
        })
      }
    })
  },


  // 发布
  goRelease() {
    wx.navigateTo({
      url: '/pages/release/release?schoolId=' + this.data.schoolId + '&chineseName=' + this.data.dataDetail.chineseName + '&type=2',
    })
  },
  goreserve() {
    wx.navigateTo({
      url: '/pages/reserve/reserve?schoolId=' + this.data.schoolId + '&schoolName=' + this.data.schoolInfo.name,
    })
  },
  copyWebUrl(e) {
    wx.setClipboardData({
      data: e.currentTarget.dataset.website,
      success: function (res) {
        wx.showToast({
          title: '复制成功',
          icon: 'success',
          duration: 2000
        })
      },
      fail: function (res) {
        wx.showToast({
          title: '复制失败',
          icon: 'none',
          duration: 2000
        })
      }
    })
  },

  downLoadPDF(e) {
    const pdfUrl = e.currentTarget.dataset.url;

    // 验证PDF URL是否存在
    if (!pdfUrl) {
      wx.showToast({
        title: '敬请期待',
        icon: 'none',
        duration: 2000
      });
      return;
    }

    // 显示下载中提示
    wx.showLoading({
      title: '正在下载PDF...',
      mask: true
    });

    // 使用异步下载API获取临时文件路径
    wx.downloadFile({
      showMenu: true,
      url: pdfUrl,
      success: (res) => {
        wx.hideLoading();
        if (res.statusCode === 200) {
          const tempFilePath = res.tempFilePath;
          const fs = wx.getFileSystemManager();
          const timestamp = Date.now();
          const savedFilePath = `${wx.env.USER_DATA_PATH}/downloaded_${timestamp}.pdf`;

          try {
            // 读取临时文件并同步写入到本地持久化目录
            const data = fs.readFileSync(tempFilePath);
            fs.writeFileSync(savedFilePath, data);
            console.log(savedFilePath);
            // 打开文档预览
            wx.openDocument({
              filePath: savedFilePath,
              fileType: 'pdf',
              showMenu: true,
              success: () => {
                wx.showToast({
                  title: '已保存并打开',
                  icon: 'success',
                  duration: 1500
                });
              },
              fail: (openErr) => {
                // console.error('打开文档失败', openErr);
                wx.showToast({
                  title: '打开文件失败',
                  icon: 'none',
                  duration: 2000
                });
              }
            });
          } catch (err) {
            // console.error('写入本地失败', err);
            wx.showToast({
              title: '保存失败',
              icon: 'none',
              duration: 2000
            });
          }
        } else {
          wx.showToast({
            title: '下载失败',
            icon: 'none',
            duration: 2000
          });
        }
      },
      fail: (err) => {
        wx.hideLoading();
        console.error('下载失败', err);
        wx.showToast({
          title: '网络异常，下载失败',
          icon: 'none',
          duration: 2000
        });
      }
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      isShare: options.type === 'share'
    });
    this.setData({
      schoolId: options.schoolId,
      userInfo: wx.getStorageSync('userInfo'),
      dictionary: wx.getStorageSync('allDicData')
    })
    this.getSchoolInfoIndex();
  },
  getSchoolInfoIndex() {
    let userId = wx.getStorageSync('userInfo') == null || wx.getStorageSync('userInfo') == "" ? 0 : this.data.userInfo.id;
    let param = {
      schoolId: this.data.schoolId,
      userId
    }
    apiGetBizSchoolsInfoPublic(param).then((res) => {
      if (res.code == 200) {
        res.school.endDate = this.getTimeDate(res.school.endDate)
        // 处理专业的语言和开学时间
        res.departments.map((item) => {
          item.professions.map((elem) => {
            if (elem.languages && elem.languages.length > 0) {
              elem.languages = elem.languages.split(',')
              elem.languages = this.getDicItem('teachlanguage', elem.languages)
            }
            if (elem.openingDates != null && elem.openingDates.length > 0) {
              elem.openingDates = elem.openingDates.split(',')
              elem.openingDates = this.getDicItem('openingDates', elem.openingDates)
            }
          })
        })
        res.videos.map((item) => {
          item.created_at = this.getTimeDate(item.created_at)
        })
        res.school.intro = this.formatContent(res.school.intro)

        // 收集所有专业的授课语言（不随筛选变化）
        let languageSet = new Set();
        res.departments.forEach(dept => {
          dept.professions.forEach(prof => {
            if (Array.isArray(prof.languages)) {
              prof.languages.forEach(lang => {
                if (lang && lang.dictValue) {
                  languageSet.add(String(lang.dictValue));
                }
              });
            }
          });
        });
        const allLangDic = this.data.dictionary['teachlanguage'] || [];
        const allLanguageList = allLangDic
          .filter(item => languageSet.has(String(item.dictValue)))
          .map(item => ({
            label: item.dictLabel,
            value: String(item.dictValue)
          }));
        this.setData({
          schoolInfo: res.school,
          videoList: res.videos,
          departmentList: res.departments,
          mentorList: res.mentors,
          schooltags: res.school.tags.split(','),
          eduPlanName: this.getDictLabel('edu_plan', res.school.eduPlanId),
          placeName: this.getDictLabel("places", res.school.placeId),
          allLanguageList // 新增：所有专业的授课语言
        })
        //学费类型
        if (res.school.placeId == 1) {
          this.setData({
            feeType: '韩元'
          })
        } else if (res.school.placeId == 2) {
          this.setData({
            feeType: '欧元'
          })
        } else if (res.school.placeId == 3) {
          this.setData({
            feeType: '新币'
          })
        } else if (res.school.placeId == 4) {
          this.setData({
            feeType: '人民币'
          })
        } else if (res.school.placeId == 5) {
          this.setData({
            feeType: '港币'
          })
        }

        let pics = res.school.pics.split(',')
        this.setData({
          swiperImages: pics.map(item => {
            return {
              url: item
            }
          })
        })
      }
    })
  },

  getDicItem(dicname, arrayValues) {
    let arr = []
    let dic = this.data.dictionary[dicname]
    arrayValues.forEach((item) => {
      let obj = dic.find((elem) => elem.dictValue == item)
      if (obj) {
        arr.push(obj)
      }
    })
    return arr
  },

  getDictLabel(dicname, value) {
    // console.log("dicname:"+dicname+"value:"+value)
    let dic = this.data.dictionary[dicname]
    if (dic != null) {
      let obj = dic.find((elem) => elem.dictValue == value)
      if (obj) {
        return obj.dictLabel
      } else {
        return ''
      }
    } else {
      return ''
    }
  },

  formatContent(html) {
    //给h1替换为p标签，style中的字体大小为28rpx ，颜色为0000000,font-weight为500
    //给h2替换 style中字体为26rpx。颜色为000000,font-weight为500
    //p标签行高伟1.8，颜色为#666D80，自题大小为26rpx
    if (html == null || html == '') {
      return ''
    }
    // console.log("html"+html);
    let newHtml = html.replace(/<p.*?>(.*?)<\/p>/g, '<p style="line-height:1.8;color:#666D80;font-size:26rpx;margin-bottom:32rpx;">$1</p>')
    newHtml = newHtml.replace(/<h1.*?>(.*?)<\/h1>/g, '<p style="font-size:28rpx;color:#000000;font-weight:500;margin-bottom:32rpx;">$1</p>')
    newHtml = newHtml.replace(/<h2.*?>(.*?)<\/h2>/g, '<p style="font-size:26rpx;color:#000000;font-weight:500;margin-bottom:32rpx;">$1</p>')
    return newHtml
  },

  // 监听页面滚动
  onPageScroll(e) {
    // e.scrollTop 是当前滚动高度
    const scrollTop = e.scrollTop;
    // 设置一个阈值，例如滚动超过200px时显示吸顶
    if (scrollTop > 100 && !this.data.showSticky) {
      this.setData({
        showSticky: true
      });
      // 添加小延迟，确保DOM先渲染，然后再添加可见性类
      setTimeout(() => {
        this.setData({
          stickyVisible: true
        });
      }, 50);
    } else if (scrollTop <= 100 && this.data.showSticky) {
      // 先执行动画，然后移除元素
      this.setData({
        stickyVisible: false
      });
      setTimeout(() => {
        this.setData({
          showSticky: false
        });
      }, 300); // 与CSS过渡时间相同
    }
  },

  formatDate(date) {
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    // 补0操作
    month = month < 10 ? '0' + month : month;
    day = day < 10 ? '0' + day : day;
    return year + '-' + month + '-' + day;
  },


  addSchoolStars(e) {
    let type = e.currentTarget.dataset.type
    let params = {
      schoolId: Number(this.data.schoolId),
      wechatUserId: this.data.userInfo.id,
      type
    }
    addUserStars(params).then((res) => {
      this.getSchoolInfoIndex()
    })
  },

  onPickerChange(e) {
    const {
      key
    } = e.currentTarget.dataset;
    const {
      value
    } = e.detail;
    console.log('picker change:', e.detail);
    this.setData({
      [`${key}Visible`]: false,
      [`${key}Value`]: value,
      [`${key}Text`]: value.join(' '),
      [`${key}Label`]: e.detail.label,
    });
    if (key == 'openDate') {
      this.setData({
        openDateLable: e.detail.label
      })
    } else {
      this.setData({
        languageLable: e.detail.label
      })
    }
    this.getProfessionList();
  },

  onPickerCancel(e) {
    const {
      key
    } = e.currentTarget.dataset;
    console.log(e, '取消');
    console.log('picker1 cancel:');
    this.setData({
      [`${key}Visible`]: false,
      [`${key}Value`]: null,
    });
    if (key == 'openDate') {
      this.setData({
        openDateLable: "开学时间",
        openDateValue
      })
    } else {
      this.setData({
        languageLable: "授课语言"
      })
    }
    this.getProfessionList()
  },

  onLanguagePicker() {
    this.setData({
      languageList: this.data.allLanguageList, // 只用初始化时收集好的全部授课语言
      languageVisible: true,
      languageTitle: '选择教学语言'
    });
  },

  onOpenDatePicker() {
    this.setData({
      openDateVisible: true,
      languageTitle: '选择开学时间'
    });

  },

  getProfessionList() {

    apiGetDepartmentBySchoolId({
      schoolId: this.data.schoolId,
      teachLanguage: this.data.languageValue == null || this.data.languageValue == '' ? '' : parseInt(this.data.languageValue),
      openingDate: this.data.openDateValue == null || this.data.openDateValue == '' ? '' : parseInt(this.data.openDateValue)
    }).then((res) => {
      if (res.data == null || res.data.length == 0) {
        this.setData({
          departmentList: null
        })
      } else {
        //循环departmentList下的schoolProfessions,把languages根据逗号分割存入数组 循环用map的写法
        res.data.map((item) => {
          item.professions.map((elem) => {
            if (elem.languages && elem.languages.length > 0) {
              elem.languages = elem.languages.split(',')
              //根据字典把教学语言翻译出来
              elem.languages = this.getDicItem('teachlanguage', elem.languages)
            }
            if (elem.openingDates != null && elem.openingDates.length > 0) {
              elem.openingDates = elem.openingDates.split(',')
              //根据字典把开学时间翻译出来
              elem.openingDates = this.getDicItem('openingDates', elem.openingDates)
            }
          })
        })
        this.setData({
          departmentList: res.data
        })
      }

    })
  },

  // 多选框变化
  onSemesterCheckboxChange(e) {
    const checked = e.detail.value;
    let openingDateId = '';
    let apiOpeningDateId = '';
    console.log("checked:" + checked.length)
    if (checked.length === 2) {
      apiOpeningDateId = "1,2";
    } else if (checked[0] === '1') {
      apiOpeningDateId = 1;
    } else if (checked[0] === '2') {
      apiOpeningDateId = 2;
    } else {
      apiOpeningDateId = '';
    }
    console.log("checked:" + checked.length)
    this.setData({
      openDatesCheckedList: checked,
      apiOpeningDateId
    }, this.querySchools);
  },




  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 刷新评论
    this.getCommentInfoList(this.data.schoolId)
  },


  deleteComment(e) {
    //如果不是自己的评论，不能删除
    if (e.currentTarget.dataset.userid !== this.data.userInfo.id) {
      return
    }
    //提醒是否删除
    wx.showModal({
      title: '提示',
      content: '确定要删除该评论吗？',
      success: (res) => {
        if (res.confirm) {
          let params = {
            id: e.currentTarget.dataset.id
          }
          deleteComment(params).then((res) => {
            if (res.code === 200) {
              this.getCommentInfoList()
            } else {
              wx.showToast({
                title: '删除失败',
              })
            }
          })
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: this.data.dataDetail.chineseName,
      path: '/pages/schools/schools?schoolId=' + this.data.schoolId + '&type=share'
    }
  }
})